package com.jinyi.base.base

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.IBinder
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import androidx.fragment.app.FragmentActivity
import com.jinyi.base.mvp.IBaseView
import com.jinyi.base.utils.ActivityStackManager
import com.jinyi.base.utils.BarUtils
import com.jinyi.base.utils.toast.ToastManager
import com.jinyi.base.weight.loading.LoadingDialog
import com.jinyi.lib_base.R
import com.jinyi.lib_base.databinding.BaseRootviewBinding


/**
 * JinYiTest
 * @Author：wwdeng
 * @CreateTime：2024/4/14 20:35
 * <pre>
 * Activity 基类
 * </pre>
 */
abstract class BaseActivity : FragmentActivity(), IBaseView {

    lateinit var rootViewBinding: BaseRootviewBinding

    /* 是否拦截返回按钮，默认不拦截直接返回 */
    private var isInterceptBack = false

    /* 退出程序提示 */
    var mExitTips = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        BarUtils.transparentStatusBar(this)
        BarUtils.setStatusBarLightMode(this, true)
        setContentView(getRootView())
        mExitTips = getString(R.string.exit_tips)
        initView()
        initListener()
        initData()
    }

    protected abstract fun getRootView(): View

    protected abstract fun initView()

    protected abstract fun initListener()

    protected abstract fun initData()

    override fun setContentView(rootView: View) {
        rootViewBinding = BaseRootviewBinding.inflate(layoutInflater)
        rootViewBinding.titlebarLayout.setPadding(0,BarUtils.getStatusBarHeight(),0,0)
        rootViewBinding.containerLayout.addView(rootView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        setTitleBarVisibility(View.GONE)
        //返回
        rootViewBinding.ivBaseBack.setOnClickListener {
            onBackAction()
        }
        super.setContentView(rootViewBinding.root)
    }

    /**
     * @功能描述：是否显示Toolbar
     */
    fun setTitleBarVisibility(visibility: Int) {
        rootViewBinding.titlebarLayout.visibility = visibility
    }


    /**
     * 设置toolBar背景颜色
     */
    fun setTitleBarColor(color: Int) {
        setTitleBarVisibility(View.VISIBLE)
        rootViewBinding.titlebarLayout.setBackgroundColor(color)
    }

    /**
     * 设置toolBar背景图片
     */
    fun setTitleBarRes(res: Int) {
        setTitleBarVisibility(View.VISIBLE)
        rootViewBinding.titlebarLayout.setBackgroundResource(res)
        rootViewBinding.titlebarLayout.setPadding(0, 0, 0, 0)
    }

    /**
     * 设置是否显示返回
     */
    fun setBackBtnVisibility(visibility: Int) {
        rootViewBinding.ivBaseBack.visibility = visibility
    }

    /**
     * 设置返回按钮图标
     */
    fun setBackBtnRes(res: Int){
        setBackBtnVisibility(View.VISIBLE)
        rootViewBinding.ivBaseBack.setImageResource(res)
    }

    /**
     * 是否显示Title
     */
    fun setTextTitleVisibility(visibility: Int){
        rootViewBinding.tvBaseTitle.visibility = visibility
    }

    /**
     * 设置Title颜色
     */
    fun setTextTitleColor(color: Int) {
        setTextTitleVisibility(View.VISIBLE)
        rootViewBinding.tvBaseTitle.setTextColor(color)
    }

    /**
     * 设置Title
     */
    fun setTextTitle(text: String) {
        setTextTitleVisibility(View.VISIBLE)
        rootViewBinding.tvBaseTitle.text = text
    }

    /**
     * 设置Title对齐方式
     * 默认：Gravity.LEFT
     */
    fun setTextTitleGravity(gravity: Int){
        setTextTitleVisibility(View.VISIBLE)
        rootViewBinding.tvBaseTitle.gravity = gravity
    }

    /**
     * 设置是否显示右侧图标
     */
    fun setRightBtnVisibility(visibility: Int){
        rootViewBinding.ivFun.visibility = visibility
    }

    /**
     * 设置右侧按钮图标
     */
    fun setRightBtnRes(res: Int){
        setRightBtnVisibility(View.VISIBLE)
        rootViewBinding.ivFun.setImageResource(res)
    }

    override fun getContext(): Context? {
        return this
    }

    override fun showLoading(msg: String?) {
        LoadingDialog.show(this, msg, true, true)
    }

    fun showLoading(msg: String?, isTOuchOut: Boolean, isCancel: Boolean) {
        LoadingDialog.show(this, msg, isTOuchOut, isCancel)
    }

    override fun hideLoading() {
        LoadingDialog.dismiss(this)
    }

    override fun showToast(s: CharSequence?) {
        showToast(s.toString())
    }

    /**
     * toast
     * @param msg
     */
    fun showToast(msg: String?) {
        ToastManager.showShortText(this, msg)
    }

    /**
     * toast
     * @param msg
     */
    fun showToastDuration(msg: String?, duration: Int) {
        ToastManager.showTextDuration(this, msg, duration)
    }

    /**
     * 设置退出程序提示语
     */
    fun setExitTips(tips: String){
        this.mExitTips = tips
    }

    /**
     * 页面跳转（不带参数）
     *
     * @param T
     */
    open fun onIntent(T: Class<*>?) {
        startActivity(Intent(this, T))
    }

    /**
     * 页面跳转（带参数）
     *
     * @param T
     * @param bundle
     */
    open fun onIntent(T: Class<*>?, bundle: Bundle?) {
        val intent = Intent(this, T)
        if (bundle != null) intent.putExtras(bundle)
        startActivity(intent)
    }

    /* 隐藏键盘 */
    fun onHideSoftInput(v: View) {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(v.windowToken, 0)
    }

    /* 显示键盘 */
    fun onShowSoftInput(v: View) {
        val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
        v.requestFocus()
    }

    // 点击外部隐藏键盘
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            val v = currentFocus
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v!!.windowToken)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = (left + v.getWidth())
            return if (event.x > left && event.x < right && event.y > top && event.y < bottom) {
                // 点击EditText的事件，忽略它。
                false
            } else {
                true
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    private fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    /* 返回 */
    fun onBackAction() {
        if (!isInterceptBack) { //不拦截，直接返回
            finish()
        }
    }

    /* 是否拦截返回按钮 */
    fun isInterceptBack(isBackExit: Boolean) {
        isInterceptBack = isBackExit
    }

    /* 向Activity中添加fragment */
    fun addContainerFragement(layout: Int, fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .add(layout, fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            //                .commitAllowingStateLoss()
            .commitAllowingStateLoss()
    }

    /* 替换Activity中的fragment */
    fun replaceContainerFragement(layout: Int, fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .replace(layout, fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /* 显示Activity中的fragment */
    fun showContainerFragement(fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .show(fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /* 隐藏Activity中的fragment */
    fun hideContainerFragement(fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .hide(fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /* 移除Activity中的fragment */
    fun removeContainerFragement(fragment: BaseFragment?) {
        supportFragmentManager
            .beginTransaction()
            .remove(fragment!!) // 此处的R.id.fragment_container是要盛放fragment的父容器
            .commitAllowingStateLoss()
    }

    /**
     * @功能描述：是否连续两次返回退出
     */
    private var isBackExit = false
    fun setBackExit(isBackExit: Boolean) {
        this.isBackExit = isBackExit
    }

    private var exitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (isBackExit) {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    showToast(mExitTips)
                    exitTime = System.currentTimeMillis()
                } else {
//                    System.exit(0);
                    ActivityStackManager.finishAllActivity()
                }
            } else {
                onBackAction()
            }
            return true
        }
        //        if (keyCode == KeyEvent.KEYCODE_BACK && mActivitys.size() == 1) {
//            startActivity(new Intent("icloudwave.hhour.home"));
//        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
//        NetworkUtils.onCancelRequest()
    }
}